import { defineStore } from 'pinia'
import { phoneLogin, logout } from '@/api/user'
import type { UserInfo } from '@/types/user'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      isShowDialog: false,
      loginForm: {
        username: '',
        password: '',
      },
      userInfo: {} as UserInfo,
      isLogin: false, //是否登录
    }
  },
  getters: {},
  actions: {
    setIsShowLogin(value: boolean) {
      this.isShowDialog = value
    },
    // 登录
    async onSubmit() {
      if (!this.loginForm.username) return ElMessage.info('手机号不能为空')
      if (!this.loginForm.password) return ElMessage.info('密码不能为空')
      const { data } = await phoneLogin(this.loginForm)
      if (data.code === 200) {
        this.userInfo = data
        this.isLogin = true
        this.setIsShowLogin(false)
      }
    },
    // 登出
    async userLogout() {
      const { data } = await logout()
      if (data.code === 200) {
        this.reset()
      }
    },

    // 重置
    reset() {
      this.$reset()
    },
  },
  // 持久化配置
  persist: {
    // 开启本项配置标识数据持久化生效
    enabled: true,
    strategies: [
      { storage: localStorage, key: 'userInfo' }, //整个状态存贮在 key 下的 localStorage 中
    ],
  },
})
